using PrintTool.Models;
using PrintTool.Services;
using System.Diagnostics;
using PrintTool.Forms;

namespace PrintTool.Forms;

public partial class MainForm : Form
{
    private List<PdfFile> pdfFiles = new();
    private List<string> availablePrinters = new();
    private bool isPrinting = false;
    private Dictionary<int, bool> columnSortOrder = new(); // 记录每列的排序方向

    // 自定义ListView类来禁用双击选择，并在编辑时阻止CheckBox交互
    private class NoDoubleClickListView : ListView
    {
        public bool IsEditing { get; set; } = false;

        protected override void WndProc(ref Message m)
        {
            // 阻止双击消息 (WM_LBUTTONDBLCLK = 0x0203)
            if (m.Msg == 0x0203)
            {
                return; // 直接阻止所有双击
            }
            base.WndProc(ref m);
        }
    }

    public MainForm()
    {
        InitializeComponent();
        LoadPrinters();
        SetupEventHandlers();
        SetupListView();
    }

    private void SetupListView()
    {
        // 设置ListView的列
        listViewFiles.Columns.Clear();
        listViewFiles.Columns.Add("✅ 选择", 80);
        listViewFiles.Columns.Add("📄 文件名", 200);
        listViewFiles.Columns.Add("📂 路径", 450);
        listViewFiles.Columns.Add("📄 页数", 80);
        listViewFiles.Columns.Add("🖨️ 副本", 80);
        listViewFiles.Columns.Add("🎨 颜色", 80);
        listViewFiles.Columns.Add("🖨️ 打印机", 140);
        listViewFiles.Columns.Add("⚙️ 操作", 260);

        // 启用CheckBox功能
        listViewFiles.CheckBoxes = true;
    }

    private void SetupEventHandlers()
    {
        btnAddFiles.Click += BtnAddFiles_Click;
        btnAddFolder.Click += BtnAddFolder_Click;
        btnClearAll.Click += BtnClearAll_Click;
        btnRemoveDuplicates.Click += BtnRemoveDuplicates_Click;
        btnPrint.Click += BtnPrint_Click;
        listViewFiles.ItemChecked += ListViewFiles_ItemChecked;
        listViewFiles.ColumnClick += ListViewFiles_ColumnClick;
        listViewFiles.MouseClick += ListViewFiles_MouseClick;
        comboPrinter.SelectedIndexChanged += ComboPrinter_SelectedIndexChanged;
        chkDefaultColor.CheckedChanged += ChkDefaultColor_CheckedChanged;
        btnCheckPrinter.Click += BtnCheckPrinter_Click;
    }

    private void LoadPrinters()
    {
        availablePrinters = PdfService.GetAvailablePrinters();
        comboPrinter.Items.Clear();
        comboPrinter.Items.AddRange(availablePrinters.ToArray());

        if (availablePrinters.Count > 0)
        {
            comboPrinter.SelectedIndex = 0;
        }
    }

    private void BtnAddFiles_Click(object? sender, EventArgs e)
    {
        using var openFileDialog = new OpenFileDialog
        {
            Filter = "PDF文件|*.pdf|所有文件|*.*",
            Multiselect = true,
            Title = "选择PDF文件"
        };

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            AddPdfFiles(openFileDialog.FileNames);
        }
    }

    private void BtnAddFolder_Click(object? sender, EventArgs e)
    {
        using var folderDialog = new FolderBrowserDialog
        {
            Description = "选择包含PDF文件的文件夹"
        };

        if (folderDialog.ShowDialog() == DialogResult.OK)
        {
            var pdfFiles = Directory.GetFiles(folderDialog.SelectedPath, "*.pdf", SearchOption.AllDirectories);
            AddPdfFiles(pdfFiles);
        }
    }

    private void AddPdfFiles(string[] filePaths)
    {
        foreach (var filePath in filePaths)
        {
            if (!PdfService.IsValidPdfFile(filePath))
            {
                MessageBox.Show($"文件 {Path.GetFileName(filePath)} 不是有效的PDF文件", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                continue;
            }

            var pdfFile = new PdfFile(filePath)
            {
                PrintCopies = (int)numDefaultCopies.Value,
                IsColorPrint = chkDefaultColor.Checked, // 使用全局颜色设置
                SelectedPrinter = comboPrinter.Text,
                IsSelected = true // 默认选中
            };

            pdfFile.PageCount = PdfService.GetPdfPageCount(filePath);
            pdfFiles.Add(pdfFile);
        }

        RefreshFileList();
        UpdateStatus();
    }

    private void RefreshFileList()
    {
        listViewFiles.Items.Clear();
        foreach (var pdfFile in pdfFiles)
        {
            var item = new ListViewItem();
            item.Checked = pdfFile.IsSelected; // 设置CheckBox状态
            item.SubItems.Add(pdfFile.FileName);
            item.SubItems.Add(pdfFile.FilePath);
            item.SubItems.Add(pdfFile.PageCount.ToString());
            item.SubItems.Add(pdfFile.PrintCopies.ToString());
            item.SubItems.Add(pdfFile.IsColorPrint ? "彩色" : "黑白");
            item.SubItems.Add(pdfFile.SelectedPrinter);
            item.SubItems.Add("【👁️ 预览】|【✏️ 编辑】|【📁 文件夹】"); // 操作列
            item.Tag = pdfFile;
            listViewFiles.Items.Add(item);
        }
        

    }

    private void BtnClearAll_Click(object? sender, EventArgs e)
    {
        if (MessageBox.Show("确定要清空所有文件吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            pdfFiles.Clear();
            RefreshFileList();
            UpdateStatus();
        }
    }

    private void BtnRemoveDuplicates_Click(object? sender, EventArgs e)
    {
        RemoveDuplicateFiles();
    }

    private void RemoveDuplicateFiles()
    {
        if (pdfFiles.Count == 0)
        {
            MessageBox.Show("文件列表为空，无需移除重复文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var originalCount = pdfFiles.Count;
        var uniqueFiles = new List<PdfFile>();
        var seenFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        foreach (var pdfFile in pdfFiles)
        {
            if (seenFileNames.Add(pdfFile.FileName))
            {
                uniqueFiles.Add(pdfFile);
            }
        }

        var removedCount = originalCount - uniqueFiles.Count;
        pdfFiles = uniqueFiles;

        RefreshFileList();
        UpdateStatus();

        if (removedCount > 0)
        {
            MessageBox.Show($"已移除 {removedCount} 个重复文件", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("没有发现重复文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    private void SortFilesByName(bool ascending = true)
    {
        pdfFiles = ascending ? 
            pdfFiles.OrderBy(f => f.FileName).ToList() : 
            pdfFiles.OrderByDescending(f => f.FileName).ToList();
        RefreshFileList();
    }

    private void SortFilesByPath(bool ascending = true)
    {
        pdfFiles = ascending ? 
            pdfFiles.OrderBy(f => f.FilePath).ToList() : 
            pdfFiles.OrderByDescending(f => f.FilePath).ToList();
        RefreshFileList();
    }

    private void SortFilesByAddedTime(bool ascending = true)
    {
        pdfFiles = ascending ? 
            pdfFiles.OrderBy(f => f.AddedTime).ToList() : 
            pdfFiles.OrderByDescending(f => f.AddedTime).ToList();
        RefreshFileList();
    }

    private void ListViewFiles_ColumnClick(object? sender, ColumnClickEventArgs e)
    {
        // 点击第一列（选择列）处理全选/取消全选
        if (e.Column == 0)
        {
            // 检查当前是否全部选中
            bool allSelected = pdfFiles.Count > 0 && pdfFiles.All(f => f.IsSelected);
            
            // 如果全部选中，则取消全选；否则全选
            foreach (var pdfFile in pdfFiles)
            {
                pdfFile.IsSelected = !allSelected;
            }
            
            RefreshFileList();
            UpdateStatus();
        }
        // 点击其他列进行排序
        else if (e.Column > 0 && e.Column < 7) // 排除操作列
        {
            SortFilesByColumn(e.Column);
        }
    }

    private void SortFilesByColumn(int columnIndex)
    {
        // 获取当前列的排序方向，如果不存在则默认为升序
        if (!columnSortOrder.ContainsKey(columnIndex))
        {
            columnSortOrder[columnIndex] = true; // true表示升序
        }
        else
        {
            columnSortOrder[columnIndex] = !columnSortOrder[columnIndex]; // 切换排序方向
        }

        bool ascending = columnSortOrder[columnIndex];
        
        // 显示排序方向提示
        string sortDirection = ascending ? "升序" : "降序";
        string columnName = GetColumnName(columnIndex);
        UpdateStatus($"已按{columnName}{sortDirection}排序");

        switch (columnIndex)
        {
            case 1: // 文件名列
                SortFilesByName(ascending);
                break;
            case 2: // 路径列
                SortFilesByPath(ascending);
                break;
            case 3: // 页数列
                pdfFiles = ascending ? 
                    pdfFiles.OrderBy(f => f.PageCount).ToList() : 
                    pdfFiles.OrderByDescending(f => f.PageCount).ToList();
                RefreshFileList();
                break;
            case 4: // 打印副本列
                pdfFiles = ascending ? 
                    pdfFiles.OrderBy(f => f.PrintCopies).ToList() : 
                    pdfFiles.OrderByDescending(f => f.PrintCopies).ToList();
                RefreshFileList();
                break;
            case 5: // 颜色列
                pdfFiles = ascending ? 
                    pdfFiles.OrderBy(f => f.IsColorPrint).ToList() : 
                    pdfFiles.OrderByDescending(f => f.IsColorPrint).ToList();
                RefreshFileList();
                break;
            case 6: // 打印机列
                pdfFiles = ascending ? 
                    pdfFiles.OrderBy(f => f.SelectedPrinter).ToList() : 
                    pdfFiles.OrderByDescending(f => f.SelectedPrinter).ToList();
                RefreshFileList();
                break;
        }
    }

    private string GetColumnName(int columnIndex)
    {
        return columnIndex switch
        {
            1 => "文件名",
            2 => "路径",
            3 => "页数",
            4 => "打印副本",
            5 => "颜色",
            6 => "打印机",
            _ => "未知列"
        };
    }

        // 双击编辑功能已禁用
        // private void ListViewFiles_DoubleClick(object? sender, EventArgs e)
        // {
        //     if (listViewFiles.SelectedItems.Count > 0)
        //     {
        //         var selectedItem = listViewFiles.SelectedItems[0];
        //         var pdfFile = (PdfFile)selectedItem.Tag;
        //     
        //         using var editForm = new PdfFileEditForm(pdfFile, availablePrinters);
        //         if (editForm.ShowDialog() == DialogResult.OK)
        //         {
        //             RefreshFileList();
        //     }
        // }
        // }

    private void ListViewFiles_ItemChecked(object? sender, ItemCheckedEventArgs e)
    {
        // 如果正在编辑，阻止选择状态改变
        if (isEditing && e.Item == editingItem)
        {
            e.Item.Checked = true; // 强制保持选中状态
            return;
        }

        if (e.Item?.Tag is PdfFile pdfFile)
        {
            pdfFile.IsSelected = e.Item.Checked;
            UpdateStatus();
        }
    }

    private void ListViewFiles_MouseClick(object? sender, MouseEventArgs e)
    {
        var hitItem = listViewFiles.GetItemAt(e.X, e.Y);
        if (hitItem != null)
        {
            var hitSubItem = hitItem.GetSubItemAt(e.X, e.Y);
            if (hitSubItem != null)
            {
                int columnIndex = hitItem.SubItems.IndexOf(hitSubItem);
                
                // 检查是否点击了打印副本列（第5列，索引为4）
                if (columnIndex == 4) // 打印副本列
                {
                    // 如果正在编辑其他行，先结束当前编辑
                    if (isEditing && editingItem != hitItem)
                    {
                        EndInlineEdit();
                    }
                    StartInlineEdit(hitItem, hitSubItem);
                }
                // 检查是否点击了操作列（第8列，索引为7）
                else if (columnIndex == 7) // 操作列
                {
                    var pdfFile = (PdfFile)hitItem.Tag;
                    HandleOperationClick(e.X, e.Y, hitItem, pdfFile);
                }
                // 如果点击了其他列且正在编辑，结束编辑
                else if (isEditing)
                {
                    EndInlineEdit();
                }
            }
        }
    }

    private void HandleOperationClick(int x, int y, ListViewItem item, PdfFile pdfFile)
    {
        // 获取操作列的边界
        var subItem = item.SubItems[7]; // 操作列
        var subItemBounds = subItem.Bounds;
        
        // 计算点击位置相对于操作列的位置
        int relativeX = x - subItemBounds.X;
        int sectionWidth = subItemBounds.Width / 3; // 将操作列分为三个部分
        
        // 根据点击位置判断操作类型
        if (relativeX < sectionWidth)
        {
            // 点击第一部分 - 预览
            OpenPdfPreview(pdfFile.FilePath);
        }
        else if (relativeX < sectionWidth * 2)
        {
            // 点击第二部分 - 编辑
            OpenPdfEditForm(pdfFile);
        }
        else
        {
            // 点击第三部分 - 打开文件夹
            OpenPdfFolder(pdfFile.FilePath);
        }
    }

    private void OpenPdfEditForm(PdfFile pdfFile)
    {
        try
        {
            using var editForm = new PdfFileEditForm(pdfFile, availablePrinters);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                RefreshFileList();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"无法打开编辑窗口: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }



    private void OpenPdfPreview(string pdfFilePath)
    {
        try
        {
            // 首先尝试使用PdfiumViewer打开PDF预览窗口
            var previewForm = new PdfPreviewForm(pdfFilePath);
            previewForm.Show();
        }
        catch (DllNotFoundException)
        {
            // 如果PdfiumViewer不可用，使用系统默认程序
            try
            {
                var processStartInfo = new ProcessStartInfo
                {
                    FileName = pdfFilePath,
                    UseShellExecute = true
                };

                Process.Start(processStartInfo);
                MessageBox.Show($"PDF文件已使用系统默认程序打开:\n{Path.GetFileName(pdfFilePath)}", 
                    "预览成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开PDF文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"无法打开PDF预览: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void OpenPdfFolder(string pdfFilePath)
    {
        try
        {
            // 获取PDF文件所在目录
            string directory = Path.GetDirectoryName(pdfFilePath) ?? "";
            
            if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
            {
                MessageBox.Show($"目录不存在: {directory}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 使用explorer.exe打开目录并定位到文件
            var processStartInfo = new ProcessStartInfo
            {
                FileName = "explorer.exe",
                Arguments = $"/select,\"{pdfFilePath}\"",
                UseShellExecute = true
            };

            Process.Start(processStartInfo);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ComboPrinter_SelectedIndexChanged(object? sender, EventArgs e)
    {
        // 更新所有文件的默认打印机设置
        foreach (var pdfFile in pdfFiles)
        {
            if (string.IsNullOrEmpty(pdfFile.SelectedPrinter))
            {
                pdfFile.SelectedPrinter = comboPrinter.Text;
            }
        }
        RefreshFileList();
    }

    private void ChkDefaultColor_CheckedChanged(object? sender, EventArgs e)
    {
        // 更新所有文件的全局颜色设置
        foreach (var pdfFile in pdfFiles)
        {
            pdfFile.IsColorPrint = chkDefaultColor.Checked;
        }
        RefreshFileList();
    }

    private void BtnCheckPrinter_Click(object? sender, EventArgs e)
    {
        CheckPrinterStatus();
    }

    private void CheckPrinterStatus()
    {
        if (string.IsNullOrEmpty(comboPrinter.Text))
        {
            MessageBox.Show("请先选择一个打印机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        var printerName = comboPrinter.Text;
        var isAvailable = PdfService.IsPrinterAvailable(printerName);
        var status = PdfService.GetPrinterStatus(printerName);

        var message = $"打印机: {printerName}\n" +
                     $"状态: {status}\n" +
                     $"可用性: {(isAvailable ? "✅ 可用" : "❌ 不可用")}";

        var icon = isAvailable ? MessageBoxIcon.Information : MessageBoxIcon.Warning;
        MessageBox.Show(message, "打印机状态检查", MessageBoxButtons.OK, icon);
    }

    private async void BtnPrint_Click(object? sender, EventArgs e)
    {
        if (isPrinting)
        {
            MessageBox.Show("正在打印中，请稍候...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var selectedFiles = pdfFiles.Where(f => f.IsSelected).ToList();
        if (selectedFiles.Count == 0)
        {
            MessageBox.Show("请选择要打印的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (MessageBox.Show($"确定要打印 {selectedFiles.Count} 个文件吗？", "确认打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            isPrinting = true;
            btnPrint.Enabled = false;
            progressBar.Visible = true;
            progressBar.Value = 0;
            lblProgress.Text = "正在打印...";

            var progress = new Progress<int>(value =>
            {
                progressBar.Value = value;
                lblProgress.Text = $"打印进度: {value}%";
            });

            try
            {
                bool success = await PdfService.PrintMultiplePdfsAsync(selectedFiles, progress);
                if (success)
                {
                    MessageBox.Show("打印完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打印过程中发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isPrinting = false;
                btnPrint.Enabled = true;
                progressBar.Visible = false;
                lblProgress.Text = "准备就绪";
            }
        }
    }



    private void UpdateStatus(string? customMessage = null)
    {
        if (!string.IsNullOrEmpty(customMessage))
        {
            statusLabel.Text = customMessage;
        }
        else
        {
            var selectedCount = pdfFiles.Count(f => f.IsSelected);
            statusLabel.Text = $"共 {pdfFiles.Count} 个文件，已选择 {selectedCount} 个";
        }
    }

    private NumericUpDown? inlineEditor = null;
    private ListViewItem? editingItem = null;
    private bool isEditing = false;



    private void StartInlineEdit(ListViewItem item, ListViewItem.ListViewSubItem subItem)
    {
        // 如果已经在编辑，先结束当前编辑
        EndInlineEdit();

        if (item.Tag is PdfFile pdfFile)
        {
            editingItem = item;
            isEditing = true; // 设置编辑状态

            // 创建内嵌编辑器
            inlineEditor = new NumericUpDown
            {
                Minimum = 1,
                Maximum = 100,
                Value = pdfFile.PrintCopies,
                Size = new Size(100, 20),
                Font = listViewFiles.Font
            };

            // 计算编辑器位置
            var subItemBounds = subItem.Bounds;
            inlineEditor.Location = new Point(subItemBounds.X, subItemBounds.Y);
            inlineEditor.Size = new Size(subItemBounds.Width, subItemBounds.Height);

            // 添加事件处理
            inlineEditor.KeyDown += InlineEditor_KeyDown;
            inlineEditor.LostFocus += InlineEditor_LostFocus;

            // 添加到ListView
            listViewFiles.Controls.Add(inlineEditor);
            inlineEditor.Focus();
            inlineEditor.Select(0, inlineEditor.Text.Length);
        }
    }

    private void InlineEditor_KeyDown(object? sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            EndInlineEdit();
        }
        else if (e.KeyCode == Keys.Escape)
        {
            CancelInlineEdit();
        }
    }

    private void InlineEditor_LostFocus(object? sender, EventArgs e)
    {
        EndInlineEdit();
    }

    private void EndInlineEdit()
    {
        if (inlineEditor != null && editingItem != null && editingItem.Tag is PdfFile pdfFile)
        {
            pdfFile.PrintCopies = (int)inlineEditor.Value;
            RefreshFileList();
            UpdateStatus();
        }
        CancelInlineEdit();
    }

    private void CancelInlineEdit()
    {
        isEditing = false; // 清除编辑状态
        
        if (inlineEditor != null)
        {
            listViewFiles.Controls.Remove(inlineEditor);
            inlineEditor.Dispose();
            inlineEditor = null;
        }
        editingItem = null;
    }
} 